﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;

namespace MyToDo.Api.Context
{
    public class MyToDoContext : DbContext
    {
        public MyToDoContext(DbContextOptions<MyToDoContext> options)
            : base(options) { }

        public DbSet<ToDo> ToDo { get; set; }
        public DbSet<User> User { get; set; }
        public DbSet<Memo> Memo { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.LogTo((s) => { Console.WriteLine(s); }
                , LogLevel.Information);
            optionsBuilder.EnableSensitiveDataLogging();
        }


        /// 修改BaseEntity中CreateDate和UpdateDate
        ///
        ///

        //protected override void OnModelCreating(ModelBuilder modelBuilder)
        //{
        //    base.OnModelCreating(modelBuilder);
        //    modelBuilder.Entity<BaseEntity>().ToTable("BaseEntity");
        //    modelBuilder.Entity<BaseEntity>(p =>
        //    {
        //        p.Property(t => t.CreateDate)
        //            .HasColumnType("DATETIME")
        //            .HasDefaultValueSql("GETDATE()");

        //        p.Property(t => t.UpdateDate)
        //            .HasColumnType("DATETIME")
        //            .HasComputedColumnSql("GETDATE()");
        //    });
        //}

        public override int SaveChanges()
        {
            updateCreateTimeAndUpdateTime();
            return base.SaveChanges();
        }
        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            updateCreateTimeAndUpdateTime();
            return base.SaveChangesAsync(cancellationToken);
        }

        /// <summary>
        /// 创建时间和更新时间处理
        /// </summary>
        private void updateCreateTimeAndUpdateTime()
        {
            var entityEntries = ChangeTracker.Entries().ToList();

            foreach (var entry in entityEntries)
            {
                if (entry.State == EntityState.Added)
                {
                    DateTime currentTime = DateTime.Now;
                    Entry(entry.Entity).Property(nameof(BaseEntity.CreateDate)).CurrentValue =
                        currentTime;
                    // 新增时也要同步更新时间
                    Entry(entry.Entity).Property(nameof(BaseEntity.UpdateDate)).CurrentValue = currentTime;
                }
                if (entry.State == EntityState.Modified)
                {
                    Entry(entry.Entity).Property(nameof(BaseEntity.UpdateDate)).CurrentValue =
                        DateTime.Now;
                }
            }
        }
    }
}
